<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
	<script type="text/javascript">
		window.socket = null;
		var reconn = false;
		if (!window.WebSocket) {
			window.WebSocket = window.MozWebSocket;
		}
		if (window.WebSocket) {

			var heartbeatTimeout = 60000
			var reconnInterval = 1000
			var lastInteractionTimeValue = 0
			var lastInteractionTime = function () {
				if (arguments.length == 1) {
					lastInteractionTimeValue = arguments[0]
				}
				return lastInteractionTimeValue
			}
			var heartbeatSendInterval = heartbeatTimeout / 2

			var count = 0;
			var connect = function () {
				window.socket = new WebSocket("ws://localhost:10000/ws");
				window.socket.onmessage = function (event) {
					var ta = document.getElementById('responseText');
					ta.value = ta.value + '\n' + event.data
					lastInteractionTime(new Date().getTime())
				};
				window.socket.onopen = function (event) {
					var ta = document.getElementById('responseText');
					ta.value = "服务器连接成功!";
					lastInteractionTime(new Date().getTime())
					window.pingIntervalId = setInterval(function () {
							ping(self)
						}, heartbeatSendInterval)
					count = 0;
				};
				window.socket.onclose = function (event) {
					clearInterval(window.pingIntervalId)
					var ta = document.getElementById('responseText');
					ta.value = "服务器异常,尝试重连连接,{重连次数:"+count+"}";
					reconn()
				};
			}

			var reconn = function (event) {
				count++
				setTimeout(function () {
					connect()
				}, reconnInterval)
			}

			var ping = function () {
				var iv = new Date().getTime() - lastInteractionTime();
				if ((heartbeatSendInterval + iv) >= heartbeatTimeout) {
					let message = {}
					message.command  = "heartbeat"
					message.data  = {}
					window.socket.send(JSON.stringify(message));
				}
			};
			connect()
		} else {
			alert("你的浏览器不支持 WebSocket！");
		}

		function send(message) {
			if (!window.WebSocket) {
				return;
			}
			if (window.socket.readyState == WebSocket.OPEN) {
				let message = {
				"command" : "noticemessage",
				"data":{
				"userName":"zhz",
				"groupId":"room1"
				}
				}
				window.socket.send(JSON.stringify(message));
			} else {
				alert("连接没有开启.");
			}
		}
	</script>
	<form onsubmit="return false;">
		<textarea id="responseText" style="width: 280px; height: 398px;"></textarea>
		<br> 
		<input type="text" name="message"  style="width: 280px" value="">
		<input type="button" value="ok" onclick="send(this.form.message.value)">
		<input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="clear">
	</form>
</body>
</html>